<template>
  <view class="chat-wrap">
    <back class="back" :back-title="backTitle" :grey="grey"></back>
    <view class="msg-list">
			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower" :scroll-into-view="toViewId" :style="{height: scrollHeight + 'px'}">
					<view v-for="(item,index) of history" :id="`x-${index}`" :key="index" class="scroll-view-item">
            <view class="time" v-if="index%10 === 0">{{parseTimeFuc(item.time)}}</view>
						<view class="me-chat" v-if="item.fromId === meId">
              <view class="msg-wrap">
                <view v-if="item.type==='text'" class="chat-box">{{item.content}}</view>
                <image v-if="item.type==='img'" :src="item.content" class="image-content" @click="handlePreview(item.url)"></image>
                <view v-if="item.type==='audio'" class="voice chat-box" @click="handlePlayVoice(item.audioUrl)">
                  <image class="voice-icon" src="/static/images/common/audio.png"></image>
                </view>
              </view>
              <view class="avatar-wrap">
                <image class="avatar" :src="userPhoto?userPhoto:desc"></image>
              </view>
						</view>
						<view v-else class="other-chat">
							<view class="avatar-wrap">
                <image class="avatar" :src="targetPhoto?targetPhoto:desc"></image>
              </view>
							<view class="msg-wrap">
                <view v-if="item.type==='text'" class="chat-box">{{item.content}}</view>
                <image v-if="item.type==='img'" :src="item.content" class="image-content" @click="handlePreview(item.url)"></image>
                <view v-if="item.type==='audio'" class="voice chat-box" @click="handlePlayVoice(item.audioUrl)">
                  <image class="voice-icon" src="/static/images/common/audio.png"></image>
                </view>
              </view>
						</view>
					</view>
			</scroll-view>
    </view>
    <view class="input-box">
      <image v-if="status === 'text'" src="/static/images/common/voice.png" class="voice" @click="handleChangeStatus"></image>
      <image v-else class="keys" src="/static/images/common/keys.png" @click="handleChangeStatus"></image>
			<view v-if="status === 'voice'" class="voice-desc" @longpress="permisionOpen" @touchend="endVoice">{{voiceText}}</view>
      <view v-else class="textarea">
        <textarea class="textarea" @focus="handleFocus" v-model="content" maxlength="-1" auto-height="true" fixed="true" show-confirm-bar="true" @input="handleInput" @confirm="handleConfirm"></textarea>
      </view>
     <!-- <image src="/static/images/common/image.png" class="image" @click="handleChangeImage"></image> -->
			<view class="button-wrap" v-if="status !== 'voice'" @click="handleSendMessage">
				<view class="send-btn">发送</view>
			</view>
    </view>
		<view v-if="isRecord" class="record-box">
			<view class="record">
				<image src="/static/images/common/record.png" mode=""></image>
				<view class="animation-box">
					<view class="animation-item"></view>
					<view class="animation-item"></view>
					<view class="animation-item"></view>
					<view class="animation-item"></view>
					<view class="animation-item"></view>
				</view>
			</view>
		</view>
  </view>
</template>

<script>
import {mapGetters} from 'vuex'
import {parseTime,deepClone, Audio2dataURL} from '../../utils/index'
import {uploadVoice} from '../../api/upload.js'
import base from  '../../api/base'
import { pathToBase64 } from '../../utils/imageTranslate.js'
import permision from "../../utils/permission.js"
// 录音对象
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();

export default {
  name: 'chat',
  data() {
    return {
      grey: true,
      backTitle: '',
			desc: '/static/images/analyze/def_user.png',
			content: '',
			scrollHeight: 0,
			status: 'text', // 当前状态
			voiceText:'按住 说话', // 语音按钮提示
			msgList: {},// 消息列表
			meId: '', // 我的ID
			targetId: '', //目标ID
			parseTimeFuc: parseTime,
			toViewId: 'x',
			currentIndex: -1, //历史记录相同ID的index
			imageUrl: [] ,// 需要上传的图片
			imgUrlArray: [],
			voicePath: '',
			voicePathArray: [],
			userPhoto: '',
			targetPhoto: '',
			historyLoading: false ,//历史数据
			page: 1,
			isUpper: false, //是否是加载历史记录动作
			isRecord: false,//开始录音
			imageBase: '' //图片base64
    }
  },
	onLoad(options) {
		const {userId, userName, userPhoto} = options
		const userInfo = JSON.parse(uni.getStorageSync('USER_INFO'))
		this.userPhoto = userInfo.userPhoto
		this.backTitle = userName ? userName : 'admin'
		this.targetPhoto = unescape(userPhoto)
		this.targetName = userName
		this.meId = userInfo.userId
		this.targetId = userId
		this.$store.dispatch('chat/updateId', userId)
		// this.initMsgList()
		// this.resetMessage()
		let self = this;
		recorderManager.onStop(function (res) {
				console.log(res)
				console.log(userInfo)
				// self.voicePath = res.tempFilePath;
				uni.uploadFile({
				    url: `${base.url}/tool/ajaxUploadSound`, //仅为示例，非真实的接口地址
				    filePath: res.tempFilePath,
				    name: 'file',
						header: {
							'Auth-id': userInfo.authId,
							'Auth-token': userInfo.authToken,
						},
				    success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data).data
							self.voicePath = data
							self.sendVoice()
				    }
				});
				// Audio2dataURL(res.tempFilePath, (e) => {
				// 	self.voicePath = e;
				// 	self.sendVoice()
				// })
		});
	},
	computed:{
		...mapGetters(['history','chatTarget']),
	},
	mounted() {
		this.autoHeight()
	},
	watch: {
		height:{
			handler: 'autoHeight',
		},
		history:{
			handler:function(val) {
				setTimeout(() => {
					this.$chatRecord(this.targetId).alreadyRead()
				}, 1000)
				if (this.isUpper) {
					this.toViewId = `x-${0}`
				} else {
					this.toViewId = `x-${val.length-1}`
				}
				
			},
			immediate: true
		},
		status(newVal,oldVal) {
			console.log(newVal,oldVal)
		}
	},
	methods: {
		// 获取焦点，到最后一个对话框
		handleFocus() {
			this.isUpper = false
		},
		upper() {
			if (this.historyLoading) {
				return
			}
			this.page+=1
			this.historyLoading = true
			this.$chatRecord(this.targetId, {}, 'text').historyRecordShow(this.page)
			this.historyLoading = false
			this.isUpper = true
		},
		lower() {
			
		},
		// 获取底部输入框高度
		autoHeight() {
			const _this = this
			const query = uni.createSelectorQuery().select('.input-box')
			query.fields({
				size: true,
				scrollOffset: true
			}, data => {
				const res = uni.getSystemInfoSync()
				_this.scrollHeight = res.windowHeight - data.height + 1
			}).exec();
		},
		// 监听底部输入框高度改变
		handleInput() {
			this.autoHeight()
		},
		//改变输入状态
		handleChangeStatus() {
			if(this.status === 'text') {
				this.status = 'voice'
			} else {
				this.status = 'text'
			}
			this.$nextTick(() => {
				this.autoHeight()
			})
		},
		// 发送消息
		handleConfirm() {
			const {status} = this
			this.sendText()
		},
		// 发送按钮
		handleSendMessage() {
			this.handleConfirm()
		},
		// 发送文字消息
		sendText() {
			const _this = this
			const userInfo = JSON.parse(uni.getStorageSync('USER_INFO'))
			if (this.content === '') return
			const extra = {
				targetName: userInfo.userName,
				targetPhoto: userInfo.userPhoto
			}
			const conversationType = this.$RongIMLib.ConversationType.PRIVATE;
			const msg = new this.$RongIMLib.TextMessage({ content: this.content, extra });
			console.log(extra)
			const pushData = '你有一条新消息';
			this.$RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, this.targetId, msg, {
					onSuccess: function (message) {
							console.log(message)
							// message 为发送的消息对象并且包含服务器返回的消息唯一 Id 和发送消息时间戳
							const messageContent = {
								fromId: message.senderUserId,
								time: message.sentTime,
								targetId: message.targetId,
								extra: {
									targetName: _this.targetName,
									targetPhoto: _this.targetPhoto
								},
								content: message.content.content
							}
							_this.isUpper = false
							_this.content = ''
							_this.$chatRecord(_this.targetId,messageContent,'text').receiveMessages()
					},
					onError: function (errorCode, message) {
						uni.uni.showToast({
							title: '消息发送失败，请稍后再试'
						});
						
					}
			}, false, pushData)
		},
		// 发送图片消息
		sendImage() {
			const _this = this;
			const userInfo = JSON.parse(uni.getStorageSync('USER_INFO'))
			const tempFilePaths = this.imageUrl;
			wx.getImageInfo({
				src: tempFilePaths,
				success(res){
					const {width, height} = res
					const base64Str = _this.imageBase;
					const imageUri = tempFilePaths; // 上传到自己服务器的 URL。
					const msg = new _this.$RongIMLib.ImageMessage({content: base64Str, imageUri: imageUri});
					const conversationType = _this.$RongIMLib.ConversationType.PRIVATE; // 单聊, 其他会话选择相应的消息类型即可
					const targetId = _this.targetId; // 目标 Id
					_this.$RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, {
							onSuccess: function (message) {
								// message 为发送的消息对象并且包含服务器返回的消息唯一 Id 和发送消息时间戳
								const messageContent = {
									fromId: message.senderUserId,
									time: message.sentTime,
									targetId: message.targetId,
									url: message.content.imageUri,
									extra: {
										targetName: _this.targetName,
										targetPhoto: _this.targetPhoto,
										width,
										height
									},
									content: message.content.content
								}
								_this.isUpper = false
								_this.$chatRecord(_this.targetId,messageContent,'img').receiveMessages()
							},
							onError: function (errorCode, message) {
								uni.uni.showToast({
									title: '图片发送失败，请稍后再试'
								});
							}
					});
				}
			})		
		},
		// 发送语音消息
		sendVoice(e) {
			const _this = this
			const userInfo = JSON.parse(uni.getStorageSync('USER_INFO'))
			const content = JSON.stringify({
				type: 3,
				url: this.voicePath
			})
			const extra = {
				targetName: userInfo.userName,
				targetPhoto: userInfo.userPhoto
			}
			const conversationType = this.$RongIMLib.ConversationType.PRIVATE;
			const msg = new this.$RongIMLib.TextMessage({ content: content, extra });
			console.log(extra)
			const pushData = '你有一条新消息';
			this.$RongIMLib.RongIMClient.getInstance().sendMessage(conversationType, this.targetId, msg, {
					onSuccess: function (message) {
							console.log(message)
							// message 为发送的消息对象并且包含服务器返回的消息唯一 Id 和发送消息时间戳
							const messageContent = {
								fromId: message.senderUserId,
								time: message.sentTime,
								targetId: message.targetId,
								extra: {
									targetName: _this.targetName,
									targetPhoto: _this.targetPhoto
								},
								content: _this.voicePath
							}
							_this.isUpper = false
							_this.content = ''
							_this.$chatRecord(_this.targetId,messageContent,'audio').receiveMessages()
					},
					onError: function (errorCode, message) {
						uni.uni.showToast({
							title: '消息发送失败，请稍后再试'
						});
						
					}
			}, false, pushData)
		},
		// 改变消息为图片状态
		handleChangeImage() {
			const userInfo = uni.getStorageSync('USER_INFO')
			this.content = ''
			const _this = this
			// this.status = 'image'
			uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function (res) {
						pathToBase64(res.tempFilePaths[0])
							.then(base64 => {
								_this.imageBase = base64
							})
							.catch(error => {
								console.error(error)
							})
						uni.uploadFile({
						    url: `${base.url}/tool/stu_par_upload`, //仅为示例，非真实的接口地址
						    filePath: res.tempFilePaths[0],
						    name: 'file',
								header: {
									'Auth-id': JSON.parse(userInfo).authId,
									'Auth-token': JSON.parse(userInfo).authToken,
								},
						    success: (uploadFileRes) => {
									const data = JSON.parse(uploadFileRes.data).data
									_this.imageUrl = data;
									_this.sendImage()
						    }
						});
					}
			});
		},
		// 图片展示
		handlePreview(path) {
			console.log(path)
			uni.previewImage({
				current: '',
				urls: [path]
			})
		},
		// 权限判断
		permisionOpen() {
			const _this = this
			uni.getSystemInfo({
				async success(res) {
					if(res.platform === 'android') {
						const isOpen = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
						const flag = isOpen === 1
							_this.isOpen(flag)
					} else {
						const isOpen = permision.judgeIosPermission("record")
						_this.isOpen(isOpen)
					}
				}
			})
		},
		isOpen(flag) {
			flag ? this.startVoice() : uni.showModal({
					title: '温馨提示',
					content: '请打开麦克风权限',
					showCancel:false,
					success: function (res) {
						permision.gotoAppPermissionSetting()
					}
			});
		},
		// 开始录音
		startVoice() {
			uni.vibrateShort({});
			recorderManager.start({
				format: 'mp3'
			})
			this.isRecord = true
		},
		//结束录音
		endVoice() {
			this.isRecord = false
			recorderManager.stop();
		},
		// 语音播放
		handlePlayVoice(src) {
			console.log(src)
			innerAudioContext.src = src
			innerAudioContext.play();
		}
	}
}

</script>
<style lang='scss' scoped>
.chat-wrap{
  width: 100%;
	height: 100vh;
	background-color: #f0f0f0;
  .back{
    position: absolute;
    top: 0;
    width: 100%;
    left:0;
  }
  .msg-list{
    width: 100%;
		.scroll-Y{
			padding-top: 154upx;
			box-sizing: border-box;
			width: 100%;
      background-color: #f0f0f0;
			.scroll-view-item{
				width: 100%;
				margin-bottom: 22upx;
			}
      .time{
        margin-bottom: 34upx;
        width: 100%;
        text-align: center;
        font-size: 30upx;
        color: #ccc;
        line-height: 32upx;
      }
			.me-chat{
				width:100%;
				display: flex;
				padding: 0 20upx 0 152upx;
        box-sizing: border-box;
        justify-content: flex-end;
				.avatar {
					width:104upx;
					height:104upx;
					border-radius:50%;
					margin-left: 33upx;
				}
				.chat-box{
          width: auto;
					background: #4495EE;
					padding: 20upx 45upx 20upx 20upx;
          box-sizing: border-box;
          flex-grow: 0;
					font-size: 30upx;
          min-height: 80upx;
          line-height: 40upx;
					color:#fff;
					max-width: 440upx;
					border-radius:10upx;
          word-break: break-word;
					position: relative;
					&::after{
						content: '';
						position: absolute;
						top: 15upx;
						right: -30upx;
						height:0;
						width:0;
						border: 20upx solid #4495EE;
						border-top-color: transparent;
						border-right-color: transparent;
						border-bottom-color: transparent;
					}
					.voice-icon{
					  transform: rotate(180deg);
						transform-origin: center;
						margin-left: 10upx;
						margin-top: 10upx;
					}
				}
			}
			.other-chat{
				width:100%;
				display: flex;
				padding: 0 152upx 0 20upx;
        box-sizing: border-box;
				.avatar {
					width:104upx;
					height:104upx;
					border-radius:50%;
					margin-right: 33upx;
				}
				.chat-box{
          width: auto;
					background: #fff;
          flex-grow: 0;
					padding: 20upx 45upx 20upx 20upx;
					box-sizing: border-box;
					font-size: 30upx;
          line-height: 40upx;
          min-height: 80upx;
					color:#333;
					max-width: 440upx;
					border-radius:10upx;
					position: relative;
          word-break: break-word;
					&::after{
						content: '';
						position: absolute;
						top: 15upx;
						left: -30upx;
						height:0;
						width:0;
						border: 20upx solid #fff;
						border-top-color: transparent;
						border-left-color: transparent;
						border-bottom-color: transparent;
					}
				}
			}
      .voice-icon{
        width: 40upx;
        height: 40upx;
      }
		}
  }
  .input-box{
    position: fixed;
    bottom:0;
    left:0;
    min-height:125upx;
    width: 100%;
    background:rgba(230,230,230,1);
    display: flex;
    align-items: center;
    padding: 25upx 20upx;
    box-sizing: border-box;
    image{
      width: 46upx;
      height:46upx;
    }
    .voice, .keys{
      margin-right: 22upx;
    }
    .image{
      margin-left: 24upx;
    }
		.voice-desc{
			flex: 1;
			height: 50upx;
			font-size: 26upx;
			color: #333;
			border:1px solid #333;
			background-color: #f0f0f0;
			text-align: center;
			line-height: 50upx;
			border-radius: 10upx;
			&:active{
				background-color: #f5f5f5;
			}
		}
    .textarea{
      border-radius:10px;
      flex: 1;
			textarea{
				width: 100%;
				font-size: 30upx;
				max-height: 200upx;
				min-height: 76upx;
				padding: 15upx 15upx;
				box-sizing: border-box;
				background-color: #fff;
			}
    }
		.button-wrap{
			width: 100upx;
			height: 50upx;
			border-radius: 4upx;
			display: flex;
			margin-left: 20upx;
			.send-btn{
				flex: 1;
				height: 100%;
				font-size: 26upx;
				color: #fff;
				background-color: limegreen;
				border:none;
				border-radius: 4upx;
				text-align: center;
				line-height: 50upx;
			}
		}
  }
}
.image-content{
	width: 120upx;
	height: 120upx;
}
.record-box{
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%,-50%);
	z-index: 100;
	.record{
		width: 200upx;
		height:200upx;
		background-color: rgba(0,0,0,0.5);
		border-radius: 6upx;
		display: flex;
		justify-content: center;
		align-items: center;
		image{
			width: 128upx;
			height:128upx;
		}
		.animation-box{
			width: 50upx;
			margin: 20upx;
			.animation-item{
				background-color: rgba(0,0,0,0.5);
				height: 10upx;
				margin-bottom: 10upx;
				&:nth-of-type(1) {
					width: 50upx;
					animation: statr 1s 1.2s infinite;
				}
				&:nth-of-type(2) {
					width: 40upx;
					animation: statr 1s 0.9s infinite;
				}
				&:nth-of-type(3) {
					width: 30upx;
					animation: statr 1s 0.6s infinite;
				}
				&:nth-of-type(4) {
					width: 20upx;
					animation: statr 1s 0.3s infinite;
				}
				&:nth-of-type(5) {
					width: 10upx;
					animation: statr 1s 0s infinite;
				}
			}
		}
	}
}
@keyframes statr{
	from {
		background-color: #fff;
	}
	to{
		background-color: rgba(0,0,0,0.5);
	}
}
</style>